package cn.zebra.dev.product.module.category.service.impl;

import cn.zebra.dev.ibatis.plus.service.impl.ServiceImpl;
import cn.zebra.dev.product.module.category.dao.ProductCategoryDao;
import cn.zebra.dev.product.module.category.entity.ProductCategoryEntity;
import cn.zebra.dev.product.module.category.service.ProductCategoryService;
import lombok.SneakyThrows;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Future;

/**
 * @author runnable@sina.cn
 */
@Service
public class ProductCategoryServiceImpl extends ServiceImpl<ProductCategoryDao, ProductCategoryEntity> implements ProductCategoryService {

    @Override
    public Boolean deleteByProductId(Long productId) {
        return this.delete("product_id = {0}", productId);
    }

    @Override
    public ProductCategoryEntity findByProductId(Long id) {
        return selectOne("product_id={0}", id);
    }

    @SneakyThrows
    @Override
    public boolean saveBatch(Collection<ProductCategoryEntity> entityList) {
        if (entityList != null && entityList.size() > 0) {
            List<Future<Boolean>> list = new ArrayList<>(entityList.size());
            entityList.forEach(entity -> list.add(this.asyncSave(entity)));
            for (int i = list.size() - 1; i >= 0; i--) {
                if (!list.get(i).get()) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    @Override
    @Async
    public Future<Boolean> asyncSave(ProductCategoryEntity entity) {
        return AsyncResult.forValue(this.save(entity));
    }
}
